package com.example.business.service;

import cn.hutool.core.bean.BeanUtil;
import com.example.common.context.UserContext;
import com.example.common.util.AdminUtil;
import com.example.common.response.PageResponse;
import com.example.business.entity.CartItem;
import com.example.business.entity.CartItemExample;
import com.example.business.mapper.CartItemMapper;
import com.example.business.request.CartItemListRequest;
import com.example.business.response.CartItemResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.util.SnowflakeUtil;
import com.example.business.request.CartItemRequest;

@Service
public class CartItemService {
    private static final Logger log = LoggerFactory.getLogger(CartItemService.class);
    @Autowired
    CartItemMapper cartItemMapper;

    @Autowired
    AdminUtil adminUtil;

    public PageResponse<CartItemResponse> list(CartItemListRequest request) {
        CartItemExample cartItemExample = new CartItemExample();
        // 按 id 字段逆序排序
        cartItemExample.setOrderByClause("id desc");

        // 查询条件
        CartItemExample.Criteria criteria = cartItemExample.createCriteria();
        if (!adminUtil.isAdmin(UserContext.getUserId())) {
            // 增加查询条件：按「当前登录用户 id 字段」进行过滤
            criteria.andUserIdEqualTo(UserContext.getUserId());
        }

        // 增加查询条件：关键词搜索
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            String keyword = "%" + request.getKeyword() + "%";
        }

        PageHelper.startPage(request.getPage(), request.getSize());
        log.info("当前页码 current_page = {}", request.getPage());
        log.info("每页记录数 per_page = {}", request.getSize());

        List<CartItem> cartItems = cartItemMapper.selectByExample(cartItemExample);

        PageInfo<CartItem> pageInfo = new PageInfo<>(cartItems);
        log.info("总记录数 total = {}", pageInfo.getTotal());
        log.info("总页数 pages = {}", pageInfo.getPages());

        List<CartItemResponse> list = BeanUtil.copyToList(cartItems, CartItemResponse.class);

        PageResponse<CartItemResponse> pageResponse = new PageResponse<>();
        pageResponse.setTotal(pageInfo.getTotal());
        pageResponse.setList(list);

        return pageResponse;
    }
    public void save(CartItemRequest request) {
        CartItem cartItem = BeanUtil.copyProperties(request, CartItem.class);
        DateTime now = DateTime.now();
        if (ObjectUtil.isNull(cartItem.getId()) || cartItem.getId() == 0L) {
            cartItem.setId(SnowflakeUtil.getId());
            cartItem.setCreatedAt(now);
            cartItem.setUpdatedAt(now);
            cartItem.setUserId(UserContext.getUserId());
            cartItemMapper.insert(cartItem);
        } else {
            cartItem.setUpdatedAt(now);
            cartItemMapper.updateByPrimaryKeySelective(cartItem);
        }
    }

    public int deleteBatch(List<Long> ids) {
        CartItemExample cartItemExample = new CartItemExample();
        CartItemExample.Criteria criteria = cartItemExample.createCriteria();
        criteria.andIdIn(ids);
        return cartItemMapper.deleteByExample(cartItemExample);
    }

    public CartItem getCartItemByProductSkuId(Long productSkuId) {
        CartItemExample cartItemExample = new CartItemExample();
        CartItemExample.Criteria criteria = cartItemExample.createCriteria();
        // 当前登录用户
        criteria.andUserIdEqualTo(UserContext.getUserId());
        criteria.andProductSkuIdEqualTo(productSkuId);

        List<CartItem> cartItems = cartItemMapper.selectByExample(cartItemExample);

        return cartItems.isEmpty() ? null : cartItems.getFirst();
    }

    public int updateCartItemAmount(CartItem cartItem) {
        CartItem selectiveCartItem = new CartItem();
        selectiveCartItem.setId(cartItem.getId());
        selectiveCartItem.setAmount(cartItem.getAmount());

        return cartItemMapper.updateByPrimaryKeySelective(selectiveCartItem);
    }
}
